import java.util.Map;
import java.util.concurrent.*;

public class CacheManager {
    // 使用ConcurrentHashMap保证线程安全
    private final Map<String, CacheItem> cacheMap = new ConcurrentHashMap<>();

    // 定时清理线程池
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    // 默认清理间隔（秒）
    private static final long DEFAULT_CLEAN_INTERVAL = 5;

    public CacheManager() {
        // 启动定期清理任务
        scheduler.scheduleAtFixedRate(this::cleanExpiredItems,
                DEFAULT_CLEAN_INTERVAL, DEFAULT_CLEAN_INTERVAL, TimeUnit.SECONDS);
    }

    // 存储缓存项（带有效期）
    public void put(String key, Object value, long ttl) {
        cacheMap.put(key, new CacheItem(value, ttl));
    }

    // 获取缓存项
    public Object get(String key) {
        CacheItem item = cacheMap.get(key);
        if (item == null || item.isExpired()) {
            remove(key);
            return null;
        }
        return item.getValue();
    }

    // 移除缓存项
    public void remove(String key) {
        cacheMap.remove(key);
    }

    // 定期清理过期项
    private void cleanExpiredItems() {
        cacheMap.entrySet().removeIf(entry ->
                entry.getValue().isExpired());
    }

    // 关闭清理任务
    public void shutdown() {
        scheduler.shutdown();
    }

    // 缓存项内部类
    private static class CacheItem {
        private final Object value;
        private final long expireTime;

        CacheItem(Object value, long ttl) {
            this.value = value;
            this.expireTime = System.currentTimeMillis() + ttl * 1000;
        }

        boolean isExpired() {
            return System.currentTimeMillis() > expireTime;
        }

        Object getValue() {
            return value;
        }
    }
}
